package cn.slipi.common.handler;

import cn.slipi.common.response.ErrorResponse;
import cn.slipi.common.response.Response;
import cn.slipi.common.utils.JsonUtil;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * lee
 * 缺陷：url错误导致的404异常无法捕捉，虽然可用配置404抛出异常但不建议这么做
 */
//@ControllerAdvice("cn.slipi.*")
public class ResponseHandler implements ResponseBodyAdvice<Object> {
    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        if (o instanceof ErrorResponse) {
            ErrorResponse errorResponse = (ErrorResponse) o;
            return Response.fail(errorResponse.getCode(), errorResponse.getMsg());
        } else if (o instanceof String) {
            return JsonUtil.object2Json(Response.success(o));
        }
        return Response.success(o);
    }
}
